package com.example.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author liyan
 */
@Controller
public class RouterController {

    /**
     * 访问首页
     *
     * @param model
     * @return
     */
    @RequestMapping({"/", "/index"})
    public String toIndex(Model model) {
        model.addAttribute("msg", "Hello Shiro");
        return "index";
    }

    /**
     * 访问登录页
     *
     * @return
     */
    @GetMapping("/login")
    public String toLogin() {
        return "login";
    }

    /**
     * 接收登陆页面提交表单，完成用户认证
     *
     * @param username
     * @param password
     * @param model
     * @return
     */
    @PostMapping("/login")
    public String login(String username, String password, String remember, Model model) {
        // 获取Subject对象currentUser
        Subject currentUser = SecurityUtils.getSubject();
        // 生成令牌
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 记住我
        token.setRememberMe(remember != null);

        try {
            // 登陆，完成用户认证
            currentUser.login(token);
            return "index";
        } catch (UnknownAccountException une) {
            model.addAttribute("msg", "用户名不存在");
        } catch (IncorrectCredentialsException ice) {
            model.addAttribute("msg", "密码错误");
        }
        return "login";
    }

    /**
     * 未授权提示
     *
     * @return
     */
    @RequestMapping("/unauthorized")
    @ResponseBody
    public String unauthorized() {
        return "未授权，无法访问";
    }

    /**
     * 注销登陆
     *
     * @return
     */
    @RequestMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "index";
    }

}
